935D - Fafa and Ancient Alphabet - CodeForces Solution


math probabilities *1900

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define int long long
using namespace std;
int mod = 1e9 +7;
int modinv_m;
int val;
int binexp(int x, int y)
{
    if(y==0)
        return 1;
    if(y&1)
        return (binexp((x*x)%mod, y/2) * x)%mod;
    else
        return (binexp((x*x)%mod, y/2))%mod;
}
int calculate(vector<int> &a, vector<int> &b, int n, int m, int i)
{
    if(i==n)
        return 0;
    for(;i<n;i++)
    {
        // cout<<a[i]<<" "<<b[i]<<endl; 
        if(a[i] == b[i] && a[i]!=0)
            continue;
        if(a[i] == b[i])
            return ((calculate(a,b,n,m,i+1) + (val*modinv_m)%mod)*modinv_m)%mod;
        else if(a[i] == 0)
        {
            // cout<<"Test\n";
            return ((calculate(a,b,n,m,i+1)+(m-b[i]))*modinv_m)%mod;
        }
        else if(b[i] == 0)
            return ((calculate(a,b,n,m,i+1)+(a[i]-1))*modinv_m)%mod;
        else if(a[i]>b[i])
            return 1;
        else
            return 0;
    }
    return 0;
}
void solve()
{
    int n, m;
    cin>>n>>m;
    modinv_m = binexp(m,mod-2)%mod;
    val = (m*(m-1))/2;
    vector<int> a(n);
    vector<int> b(n);
    for(int i=0;i<n;i++)
        cin>>a[i];
    for(int i=0;i<n;i++)
        cin>>b[i];
    int p = (calculate(a,b,n,m,0))%mod;
    cout<<p<<endl;
}
int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t=1;
    // cin>>t;
    for(int i=1;i<=t;i++)
    {
        // cout<<"Testcase: "<<i<<endl;
        solve();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1673A - Subtle Substring Subtraction
1345A - Puzzle Pieces
711A - Bus to Udayland
779B - Weird Rounding
1703D - Double Strings
1704C - Virus
63A - Sinking Ship
1704B - Luke is a Foodie
298B - Sail
239A - Two Bags of Potatoes
1704E - Count Seconds
682A - Alyona and Numbers
44A - Indian Summer
1133C - Balanced Team
1704A - Two 0-1 Sequences
1467A - Wizard of Orz
1714E - Add Modulo 10
1714A - Everyone Loves to Sleep
764A - Taymyr is calling you
1714B - Remove Prefix
1264F - Beautiful Fibonacci Problem
52A - 123-sequence
1543A - Exciting Bets
1714D - Color with Occurrences
215B - Olympic Medal
1445A - Array Rearrangment
1351A - A+B (Trial Problem)
935B - Fafa and the Gates
1291A - Even But Not Even
1269A - Equation